<?php
    include 'include/function.php';
	if (isset($_POST['submit'])){
		$user_id = $_POST['user_id'];
		$password = $_POST['password'];
		$repeatpassword = $_POST['repeatpassword'];
		$nick = $_POST['nick'];
		$email = $_POST['email'];
		$school = $_POST['school'];
	}
	else
		header("Location: register");
	$errorMsg = '';
	if (empty($user_id))
		$errorMsg = "User ID can not be NULL";
    else if (strlen($user_id) < 3)
        $errorMsg = "User ID is too short";
	else if (strlen($user_id) > 20)
		$errorMsg = "User ID is too long";
	else {
		for($i = 0; $i < strlen($user_id); $i++)
		    if ($user_id{$i} != '_' && !($user_id{$i} >= '0' && $user_id{$i} <= '9')
			    && !($user_id{$i}>= 'A' && $user_id{$i} <= 'Z')
			    && !($user_id{$i} >= 'a' && $user_id{$i} <='z'))
				break;
		if ($i != strlen($user_id))
			$errorMsg = 'User ID can only contain number, letter and _';
		else if (empty($password))
			$errorMsg = "Password can not be NULL";
		else if(strlen($password) != 32)
			$errorMsg = "Please make sure that you have enabled the javascript";
		else if ($password != $repeatpassword)
			$errorMsg = "Password do not match";
		else if (exist_user($user_id))
			$errorMsg = "User $user_id already exists";
        if (get_magic_quotes_gpc()) {
            $nick = stripslashes($nick);
            $email = stripslashes($email);
            $school = stripslashes($school);
        }
        $nick = mysql_escape_string($nick);
        $email = mysql_escape_string($email);
        $school = mysql_escape_string($school);
        if (strlen($nick) > 100)
            $errorMsg = "Your nick name is too long";
        else if (strlen($email) > 100)
            $errorMsg = "Your email is too long";
        else if (strlen($school) > 100)
            $errorMsg = "Your school name is too long";
	}

	if (!empty($errorMsg)){
		header("Location: error?error=" . urlencode($errorMsg));
		exit;
	}
	if (register($user_id, $password, $nick, $email, $school)) {
		header("Location: error?error=" . urlencode("Register success, please contact the admin to validate your ID"));
		exit;
	}
	else {
		header("Location: error?error=" . urlencode("Sorry, system is busy"));
		exit;
	}
?>
